import {
  generateHtmlContent,
  generateIconfontContent,
  generateSymbolContnt,
} from "./templates";
import { getIconfontContent, getOutputPath, readSvgFiles } from "./tools";
import { IOptions, ISvgOptions } from "./types";
const fs = require("fs");
const path = require("path");

export function addSvgs(options: IOptions) {
  const { add, inputValue } = options;
  if (typeof add !== "string") {
    throw new Error("add must be a string");
  }
  if (typeof inputValue !== "string") {
    throw new Error("input must be a string");
  }
  if (!inputValue.endsWith(".js")) {
    throw new Error("input must be a .js file");
  }
  const inputPathList: string[] = (inputValue || "").split("/").filter(Boolean);
  const inputPath = path.join(process.cwd(), ...inputPathList);
  if (!fs.existsSync(inputPath) || !fs.statSync(inputPath).isFile()) {
    throw new Error(`Input path ${inputPath} does not exist or is not a file`);
  }
  const { svgId, svgList: oldSvgList } = getIconfontContent(inputPath);
  const newSvgList = addNewSvgs(options);
  const svgMap = oldSvgList.reduce((prev, cur) => {
    prev[cur.name] = cur;
    return prev;
  }, {} as any);
  newSvgList.forEach((svg) => {
    const { name } = svg;
    if (svgMap[name]) {
      svg.name = findNoRepeatName(svgMap, svg.name);
    }
    svgMap[svg.name] = svg;
  });
  const svgList = Object.keys(svgMap).map((name) => svgMap[name]);
  outputFile(svgId, svgList, options);
}

function findNoRepeatName(svgMap: any, name: string) {
  let nName = name;
  while (svgMap[nName]) {
    nName = `${nName}-1`;
  }
  return nName;
}

// 读取要添加的svg文件
function addNewSvgs(options: IOptions): ISvgOptions[] {
  const { add, isPure, isDeep } = options;
  let svgList: ISvgOptions[] = [];
  const addPathList: string[] = (add || "").split("/").filter(Boolean);
  const addPath = path.join(process.cwd(), ...addPathList);
  if (!fs.existsSync(addPath)) {
    throw new Error(`add path ${addPath} not exist`);
  }
  if (fs.statSync(addPath).isFile()) {
    if (!add?.endsWith(".svg")) {
      throw new Error("add must be a svg file");
    }
  }

  svgList = readSvgFiles(addPath, { isDeep, isPure });
  return svgList;
}
// 输出iconfont.js文件
function outputFile(svgId: string, svgList: ISvgOptions[], options: IOptions) {
  const { outputValue, inputValue } = options;
  let out = outputValue;
  // 如果没有指定output文件就直接修改源文件目录
  if (!out) {
    out = inputValue;
  }
  const outputPath = getOutputPath(out, "iconfont.js", ".js");
  const content = generateIconfontContent(
    svgList.map(generateSymbolContnt).join(""),
    svgId
  );
  fs.writeFileSync(outputPath, content);
  const html = generateHtmlContent(svgList.map((item) => item.name));
  const htmlPath = path.join(path.parse(outputPath).dir, "index.html");
  fs.writeFileSync(htmlPath, html);
}
